package com.ajaxlord.confluence.extlink;

import com.atlassian.confluence.renderer.WikiRendererContextKeys;
import com.atlassian.renderer.links.GenericLinkParser;
import com.atlassian.renderer.links.UrlLink;
import com.atlassian.renderer.macro.BaseMacro;
import org.radeox.macro.parameter.MacroParameter;
import org.radeox.util.Encoder;

import java.io.IOException;
import java.io.Writer;
import java.text.ParseException;

public class ExtLinkMacro extends BaseMacro {

    public ExtLinkMacro() {
    }

    public String getName() {
        return "extlink";
    }

    public String[] getParamDescription() {
        return myParamDescription;
    }

    public void execute(Writer writer, MacroParameter macroParameter)
            throws IllegalArgumentException, IOException {
        com.atlassian.confluence.renderer.PageContext pageContext = WikiRendererContextKeys.getPageContext(macroParameter.getContext().getParameters());
        String text = macroParameter.get("text", 0);
        String url = macroParameter.get("url", 1);
        String target = macroParameter.get("target", 2);
        if (macroParameter.getLength() == 1) {
            url = text;
            text = Encoder.toEntity(text.charAt(0)) + text.substring(1);
        }
        if (url == null && text == null)
            throw new IllegalArgumentException("link needs a name and a url as argument");
        StringBuffer buffer = new StringBuffer();
        try {
            //skip permission check...
            //TODO Fix
            String renderedLink = pageContext.getLinkRenderer().renderLink(new UrlLink(url, text), pageContext);
            if (target != null) renderedLink = renderedLink.replaceAll("<a href", "<a target=\"" + target + "\" href");
            buffer.append(pageContext.getRenderedContentStore().addInline(renderedLink));
            pageContext.addExternalReference(new UrlLink(new GenericLinkParser(url)));
        }
        catch (ParseException e) {
            buffer.append(url);
        }
        writer.write(buffer.toString());
    }

    //TODO add more parameter support
    private String myParamDescription[] = {
            "1: text", "?2: url", "?3: target"
    };
}